<script setup lang="ts">
import { ref } from 'vue'
import dayjs from 'dayjs'
import { getadvanceapplylistapi, getuserapplyconfigapi, postadvanceapplyapi } from '@/package-advance/api/advance/advance'

const tabList = ref([
    {
        text: '预支申请',
        value: 0,
    },
    {
        text: '预支记录',
        value: 1,
    },
])
const pageNum = ref(1)
const pageSize = ref(10)
const date = ref(dayjs().format('YYYY-MM'))
const advancehistorylist = ref([] as any)
const hasnext = ref(true)
const totalAmount = ref(0)
const idcard = ref('')
const fileList = ref([] as any)
const remark = ref('')
const cgmaxflag = ref(false)
const popup = ref()
const popupCenter = ref()
const active = ref(0)
const companyName = ref('')
const companyId = ref(0)
const serveCompanyId = ref(0)
const serveCompanyName = ref('')
const maxprice = ref(0)
const infoarr = ref<any>([])
const advanceprice = ref('' as string | number)
const oktoadvance = ref(true)
const selectIndex = ref('')
function onCall(val: string) {
    if (val) {
        uni.makePhoneCall({
            phoneNumber: val,
        })
    }
    else {
        uni.showToast({
            icon: 'none',
            title: '暂无驻场手机号',
        })
    }
}
const popselectarr = ref([] as any)
function tojl() {
    active.value = 1
    pageNum.value = 1
    hasnext.value = true
    advancehistorylist.value = []
    popupCenter.value.close()
    getadvanceapplylist()
}
async function postadvanceapply(result?: any) {
    const res = await postadvanceapplyapi({
        companyId: companyId.value,
        companyName: serveCompanyName.value,
        serveCompanyId: serveCompanyId.value,
        advanceAmount: advanceprice.value,
        applyRemark: remark.value,
        files: result,
    })
    popupCenter.value.open('center')
}
async function gotoadvance() {
    if (remark.value)
        remark.value = remark.value.replace(/\s/g, '')

    if (/\s+/.test(remark.value)) {
        toast('备注不可输入多个空格')
        return
    }
    if (/\.\./.test(remark.value)) {
        toast('备注不可输入多个.')
        return
    }
    if (!remark.value) {
        toast('请输入备注')
        return
    }
    if (serveCompanyName.value === '') {
        toast('请选择用工企业')
        return
    }
    if (cgmaxflag.value) {
        toast('超出公司最大预支金额')
        return
    }
    if (advanceprice.value === 0 || advanceprice.value === null) {
        toast('请输入预支金额')
        return
    }
    const promiseList = []
    for (const i in fileList.value)
        promiseList.push(wxfileTobase64(fileList.value[i]))

    const result = await Promise.all(promiseList)
    postadvanceapply(result)
}
function changeprice(e: any) {
    const value = validateNumber(e.detail.value) * 1
    console.log(value)
    if (value > maxprice.value)
        cgmaxflag.value = true
    else
        cgmaxflag.value = false
    advanceprice.value = value
}
function getuserapplyconfig() {
    getuserapplyconfigapi().then((res) => {
        console.log(res, 'syufguyf')
        if (!res.companyId) {
            oktoadvance.value = false
            return
        }
        if (!res.companyName) {
            oktoadvance.value = false
            return
        }
        if (!res.serveCompanyList) {
            oktoadvance.value = false
            return
        }
        if (res.serveCompanyList.length === 0) {
            oktoadvance.value = false
            return
        }
        if (!res.id) {
            oktoadvance.value = false
            return
        }
        infoarr.value = res.serveCompanyList
        popselectarr.value = res.serveCompanyList.map((item: any) => {
            return item.serveCompanyName
        })
        maxprice.value = res.applyQuota
        companyId.value = res.companyId
        companyName.value = res.companyName
    })
}
function changetab(i: number) {
    active.value = i
}

function onChoose() {
    // 打开弹窗
    popup.value.open('bottom')
}
function validateNumber(val: any) {
    if (!val)
        return 0
    return val.replace(/\s*/g, '').replace(/\D/g, '')
}
function onChangeserveCompany(val: any) {
    const i = val.detail.value
    selectIndex.value = i
    serveCompanyName.value = infoarr.value[i].serveCompanyName
    serveCompanyId.value = infoarr.value[i].id
    // popup.value.close()
}
async function onUpload() {
    const result = await uni.chooseImage({
        count: 2,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
    })
    fileList.value = result.tempFilePaths
}
function onClosePopCenter() {
    popupCenter.value.close()
    uni.navigateBack({
        delta: 1,
    })
}
function getadvanceapplylist() {
    if (hasnext.value) {
        getadvanceapplylistapi({
            idCardNo: idcard.value,
            queryMonth: date.value,
            pageSize: pageSize.value,
            pageNum: pageNum.value,
        }).then((res) => {
            console.log(res)
            res.list.forEach((ele: any, i: number) => {
                ele.payTime = dayjs(ele.payTime).format('YYYY-MM-DD-HH:mm:ss')
                // 0 ：审核中 1:未通过 2:待领取 3：已领取 4：停止 5：失败 6:进行中
                if (ele.applyStatus === 0
                  || (ele.applyStatus === 1 && (ele.auditStatus === null || ele.auditStatus === 0) && ele.status !== 1)) {
                    ele.endstatus = 0
                }
                else if (ele.applyStatus === 1 && ele.auditStatus === 1) {
                    // 根据status值分配不同的endstatus
                    switch (ele.status) {
                        case 0:
                            ele.endstatus = 2
                            break
                        case 1:
                            ele.endstatus = 3
                            break
                        case 2:
                            ele.endstatus = 4
                            break
                        case 3:
                            ele.endstatus = 6
                            break
                        case 4:
                            ele.endstatus = 5
                            break
                        default:
                            // 其他情况不改变endstatus或设置默认值
                            break
                    }
                }
                else if (ele.applyStatus === 2 || (ele.applyStatus === 1 && ele.auditStatus === 2)) {
                    ele.endstatus = 1
                }
                // if (ele.applyStatus === 0 && ele.auditStatus === null && ele.status === null)
                //     ele.endstatus = 0
                // else if (ele.applyStatus === 1 && ele.auditStatus === null && ele.status === null)
                //     ele.endstatus = 0
                // else if (ele.applyStatus === 1 && ele.auditStatus === 0 && ele.status === null)
                //     ele.endstatus = 0
                // else if (ele.applyStatus === 1 && ele.auditStatus === 0 && ele.status === 0)
                //     ele.endstatus = 0
                // else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 1)
                //     ele.endstatus = 3
                // else if (ele.applyStatus === 2 && ele.auditStatus === null && ele.status === null)
                //     ele.endstatus = 1
                // else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 0)
                //     ele.endstatus = 2
                // else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 2)
                //     ele.endstatus = 4
                // else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 3)
                //     ele.endstatus = 6
                // else if (ele.applyStatus === 1 && ele.auditStatus === 1 && ele.status === 4)
                //     ele.endstatus = 5
                // else if (ele.applyStatus === 1 && ele.auditStatus === 2 && ele.status === null)
                //     ele.endstatus = 1
                // else if (ele.applyStatus === 1 && ele.auditStatus === 2 && ele.status === 0)
                //     ele.endstatus = 1
            })
            const arr: any = (advancehistorylist.value as any).concat(res.list)
            hasnext.value = res.hasNextPage
            advancehistorylist.value = arr
            totalAmount.value = res.totalAmount
        })
    }
}
function todetail(val: number | string) {
    console.log(val, 'sdgybygf')
    uni.navigateTo({
        url: `/package-mine/pages/advance-details/advance-details?id=${val}&showBottom=${'0'}`,
    })
}
function onNextpPage() {
    pageNum.value++
    getadvanceapplylist()
}
function bindDateChange(val: any) {
    console.log(val)
    // date.value = val.detail.value
    date.value = dayjs(val.detail.value).format('YYYY-MM')
    pageNum.value = 1
    advancehistorylist.value = []
    hasnext.value = true
    getadvanceapplylist()
}
onLoad(() => {
    user.waitLogin().then((res) => {
        idcard.value = user.userInfo.value.idCardNo
        getadvanceapplylist()
        getuserapplyconfig()
    })
})
</script>

<template>
    <NavbarContainer nav-title="我要预支">
        <view class="box-border min-h-100vh w-full">
            <view class="tabbar">
                <view v-for="(item, i) in tabList" :key="i" class="bar" @click="changetab(item.value)">
                    <view class="text" :class="{ activetext: active === item.value }">{{ item.text }}</view>
                    <view class="line" :class="{ activeline: active === item.value }" />
                </view>
            </view>
            <view v-if="active === 1">
                <scroll-view class="scroll-h" :scroll-y="true" :refresher-enabled="true" @scrolltolower="onNextpPage">
                    <view class="list">
                        <view class="timeandtotal">
                            <picker mode="date" header-text="选择时间" fields="month" value="{{date}}" @change="bindDateChange">
                                <view class="flex items-center">
                                    <text class="text-44rpx font-600">{{ date }}</text>
                                    <text class="timeIcon">▼</text>
                                </view>
                            </picker>
                            <view class="total">
                                <text>共预支</text><text style="font-weight: 600;margin-left: 10rpx;">
                                    ¥
                                    {{ totalAmount }}
                                </text>
                            </view>
                        </view>
                        <view v-if="advancehistorylist.length !== 0" class="listitembox">
                            <view v-for="(item, i) in advancehistorylist" :key="i" class="listitem"
                                  @click="todetail(item.id)">
                                <view class="advancecontent">
                                    <view class="title">
                                        <text v-if="item.endstatus === 0" class="tagyellow">
                                            审核中
                                        </text><text v-if="item.endstatus === 6" class="tagyellow">
                                            进行中
                                        </text><text v-if="item.endstatus === 2" class="taggreen">
                                            待领取
                                        </text><text v-if="item.endstatus === 3" class="taggreen">
                                            已领取
                                        </text><text v-if="item.endstatus === 1" class="tagred">
                                            未通过
                                        </text><text v-if="item.endstatus === 4" class="tagred">
                                            已停止
                                        </text><text v-if="item.endstatus === 5" class="tagred">
                                            领取失败
                                        </text><text class="jobname">
                                            {{ item.serveCompanyName }}
                                        </text>
                                    </view>
                                    <view class="time">
                                        <text class="timelable">申请日期：</text>
                                        {{ item.advanceApplyTime ? item.advanceApplyTime : '--' }}
                                    </view>
                                    <view v-if="item.endstatus === 3" class="time">
                                        <text class="timelable">领薪日期：</text>
                                        {{ item.getSalaryTime ? item.getSalaryTime : '--' }}
                                    </view>
                                    <view v-if="item.endstatus === 4" class="time">
                                        <text class="timelable">停发日期：</text>
                                        {{ item.stopTime ? item.stopTime : '--' }}
                                    </view>
                                    <view v-if="item.endstatus === 5" class="time">
                                        <text class="timelable">失败原因：</text>
                                        {{ item.operRemark ? item.operRemark : '--' }}
                                    </view>
                                    <view v-if="item.endstatus === 2" class="time">
                                        <text class="timelable">发放日期：</text>
                                        {{ item.payTime ? item.payTime : '--' }}
                                    </view>
                                </view>
                                <view class="advancestatus">
                                    <view class="price">¥{{ item.advanceAmount }}</view>
                                    <view
                                        v-if="(item.endatus === 0 && !!item.isShowContacts) || (item.endstatus === 1 && !!item.isShowContacts)"
                                        class="btn" @click="onCall(item.phone)">
                                        <image class="img" src="../../img/phoneicon.png" mode="widthFix" />
                                        联系驻场
                                    </view>
                                    <image v-if="item.auditStatus === 1" class="stsimg" src="../../img/passTheAudit.png"
                                           mode="widthFix" />
                                </view>
                            </view>
                        </view>
                        <view v-else class="box-border w-full pt-350rpx text-center">暂无数据</view>
                    </view>
                </scroll-view>
            </view>
            <view v-if="active === 0" class="content">
                <view v-if="!oktoadvance" class="nodatabox">
                    <image class="nodatapng" src="../../img/nodata.png" mode="heightFix" />
                    <view class="text">您未在可预支的名单中</view>
                    <view class="text">如需预支请联系驻厂添加</view>
                </view>
                <view v-if="oktoadvance">
                    <view class="mt-24rpx box-border w-full bg-#ffffff p-32rpx">
                        <view class="mb-24rpx text-28rpx text-#565868">当前所属劳务公司</view>
                        <view class="text-32rpx text-#202536 font-700">{{ companyName }}</view>
                    </view>
                    <view class="mt-24rpx box-border w-full bg-#ffffff p-32rpx">
                        <view class="mb-24rpx text-28rpx text-#565868">当前用工企业</view>
                        <picker :value="selectIndex" :range="popselectarr" @change="onChangeserveCompany">
                            <view class="text-32rpx font-700"
                                  :class="{ 'text-#202536': serveCompanyName !== '', 'text-#C9CBD8': serveCompanyName === '' }"
                                  @click="onChoose">
                                {{ serveCompanyName === '' ? '请选择当前用工企业' : serveCompanyName }}
                            </view>
                        </picker>
                    </view>
                    <view class="mt-24rpx box-border w-full bg-#ffffff p-32rpx">
                        <view class="mb-24rpx text-28rpx text-#565868">预支金额</view>
                        <view class="box-border w-full flex items-center text-32rpx text-#202536 font-700">
                            <view>￥</view>
                            <input v-model="advanceprice" type="number" class="flex-1"
                                   :placeholder="`请输入金额（最大预支金额${maxprice}元）`" @input="changeprice">
                        </view>
                        <view v-if="cgmaxflag" class="maxnum myorigin">* 超过最大预支金额，请输入{{ maxprice }}元以内的金额</view>
                    </view>
                    <view class="mt-24rpx box-border w-full bg-#ffffff p-32rpx">
                        <view class="mb-24rpx text-28rpx text-#565868">备注</view>
                        <input v-model="remark" type="text" class="box-border w-full text-32rpx text-#202536 font-700"
                               placeholder="请输入备注，不超过30字" maxlength="30">
                    </view>
                    <view class="mt-24rpx box-border w-full bg-#ffffff p-32rpx">
                        <view class="mb-24rpx text-28rpx text-#565868">上传证明附件<span class="text-#C9CBD8">（非必填）</span></view>
                        <view class="mb-24rpx text-28rpx text-#C9CBD8">最多上传2张，支持JPG、PNG格式</view>
                        <image v-for="(item, i) in fileList" :key="i" class="mr-20rpx h-160rpx w-160rpx" :src="item" />
                        <img class="mr-20rpx h-160rpx w-160rpx" mode="widthFix" src="../../img/image-uploader-cell.png"
                             @click="onUpload">
                    </view>
                    <view class="box-border w-full px-32rpx">
                        <view
                            class="box-border h-88rpx w-full flex items-center justify-center rounded-44rpx bg-#3E5FF5 text-32rpx text-#ffffff"
                            @click="gotoadvance">
                            我要预支
                        </view>
                    </view>
                </view>
            </view>
            <!-- <uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0" background-color="#fff">
            <view class="h-35vh w-full">
                <view class="box-border h-60rpx w-full flex items-center justify-center font-bold">请选择当前用工企业</view>
                <view class="pop-h w-full flex flex-col justify-center gap-20rpx">
                    <view v-for="(item, i) in infoarr" :key="i"
                          class="w-full flex items-center justify-center py-20rpx text-36rpx font-600"
                          @click="onChangeserveCompany(item.serveCompanyName, item.id)">
                        {{ item.serveCompanyName }}
                    </view>
                </view>
            </view>
        </uni-popup> -->
            <uni-popup ref="popupCenter" type="center" border-radius="20rpx 20rpx 20rpx 20rpx" background-color="#fff">
                <view class="min-h-30vh w-90vw">
                    <view
                        class="mb-60rpx box-border h-60rpx w-full flex items-center justify-center pt-30rpx text-36rpx font-bold">
                        预支申请提交成功
                    </view>
                    <view class="mb-40rpx px-60rpx text-center text-32rpx text-#9497B1">
                        等待公司审批，您可在<span class="text-#202536">「预支记录」</span>中查看自己的预支申请进度
                    </view>
                    <view class="flex items-center justify-center gap-20rpx px-60rpx">
                        <view class="btn1" @click="tojl">去查看</view>
                        <view class="btn2" @click="onClosePopCenter">我知道了</view>
                    </view>
                </view>
            </uni-popup>
        </view>
    </NavbarContainer>
</template>

<style scoped>
.btn1,
.btn2 {
    width: 264rpx;
    height: 88rpx;
    border-radius: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 36rpx;
}

.btn1 {
    color: #202536;
    border: 1px solid #E8E9EA;
    background-color: #ffffff;
}

.btn2 {
    color: #ffffff;
    background-color: #3E5FF5;
    border: 1px solid #3E5FF5;
}

.nodatapng {
    margin-top: 240rpx;
    margin-bottom: 10rpx;
    width: 200rpx;
    height: 224rpx;
}

.maxnum {
    margin-top: 32rpx;
    color: #202536;
    font-size: 24rpx;
}

.myorigin {
    color: #FF7642 !important;
}

.pop-h {
    height: calc(35vh - 40rpx);
    box-sizing: border-box;
    overflow: scroll;
    padding-top: 40rpx;
}

.activetext {
    font-weight: 700;
    font-size: 36rpx;
    color: #4C7BFF !important;
}

.nodatabox .text {
    font-size: 28rpx;
    margin-top: 10rpx;
    color: #9497B1;
}

.nodatabox {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.activeline {
    background-color: #4C7BFF !important;
}

.tabbar {
    width: 100%;
    height: 92rpx;
    background-color: #FFFFFF;
    color: #9497B1;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    box-shadow: 0rpx 1rpx 2rpx 0rpx rgba(209, 209, 209, 0.5);
}

.tabbar .bar {
    box-sizing: border-box;
    height: 100%;
    width: 50%;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
}

.tabbar .bar .text {
    padding-top: 20rpx;
    flex: 1;
    display: flex;
    align-items: center;
}

.tabbar .bar .line {
    width: 40rpx;
    height: 8rpx;
    background-color: #FFFFFF;
    margin-top: 24rpx;
    border-radius: 4rpx;
}

.tabboxr .nodate {
    height: 100%;
    width: 100%;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    flex-direction: column;
}

.tabboxr .nodate image {
    margin-top: 240rpx;
    width: 200rpx;
    height: 224rpx;
    margin-bottom: 48rpx;
}

.tabboxr .nodate .text {
    text-align: center;
    width: 308rpx;
    color: #9497B1;
    font-size: 28rpx;
}

.list {
    width: 100%;
    box-sizing: border-box;
    height: 100%;
    background-color: #FAFAFC;
}

.list .timeandtotal {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx;
}

.list .timeandtotal .time {
    color: #202536;
    font-size: 44rpx;
    font-weight: 500;
}

.list .timeandtotal .total {
    color: #202536;
    font-size: 28rpx;
    display: flex;
    align-items: center;
}

.listitembox {
    width: 100%;
    box-sizing: border-box;
    padding: 10rpx 32rpx;
}

.listitem {
    box-sizing: border-box;
    width: 100%;
    min-height: 196rpx;
    background-color: #FFFFFF;
    border-radius: 16rpx;
    margin-bottom: 32rpx;
    padding: 28rpx 32rpx;
    display: flex;
    justify-content: space-between;
}

.listitem .advancecontent {
    width: 70%;
}

.listitem .advancecontent .title .tagyellow {
    margin-right: 24rpx;
    box-sizing: border-box;
    padding: 8rpx 12rpx;
    min-width: 72rpx;
    height: 40rpx;
    border-radius: 8rpx;
    font-size: 24rpx;
    text-align: center;
    line-height: 40rpx;
    color: #FFC142;
    background: #FFF8EC;
}

.listitem .advancecontent .title .taggreen {
    margin-right: 24rpx;
    box-sizing: border-box;
    padding: 8rpx 12rpx;
    min-width: 72rpx;
    height: 40rpx;
    border-radius: 8rpx;
    font-size: 24rpx;
    text-align: center;
    color: #04CD5A;
    background: #E5F9EE;
    line-height: 40rpx;
}

.listitem .advancecontent .title .tagred {
    margin-right: 24rpx;
    box-sizing: border-box;
    padding: 8rpx 12rpx;
    min-width: 72rpx;
    height: 40rpx;
    border-radius: 8rpx;
    font-size: 24rpx;
    text-align: center;
    line-height: 40rpx;
    background: #FFE6E9;
    color: #F6445F;
}

.listitem .advancecontent .title .jobname {
    font-size: 32rpx;
    color: #202536;
    font-weight: 600;
}

.listitem .advancecontent .title {
    margin-bottom: 24rpx;
}

.listitem .advancecontent .time {
    color: #202536;
    font-size: 24rpx;
    margin-bottom: 24rpx;
}

.listitem .advancecontent .time .timelable {
    color: #9497B1;
}

.listitem .advancestatus {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    width: 30%;
}

.listitem .advancestatus .price {
    color: #FF7642;
    font-weight: 600;
    font-size: 36rpx;
}

.listitem .advancestatus .btn {
    box-sizing: border-box;
    width: 180rpx;
    margin-top: 40rpx;
    height: 56rpx;
    line-height: 56rpx;
    background-color: #4C7BFF;
    box-sizing: border-box;
    text-align: center;
    color: #FDFDFF;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    font-size: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.listitem .advancestatus .btn .image {
    margin-right: 15rpx;
    width: 24rpx;
    height: 24rpx;
}

.listitem .advancestatus .stsimg {
    width: 176rpx;
    height: 176rpx;
}

.darkwindow {
    z-index: 90;
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    background: rgba(27, 27, 27, 0.67);
    display: flex;
    align-items: center;
    justify-content: center;
}

.darkwindow .agreementbox {
    position: relative;
    width: 620rpx;
    height: 1098rpx;
}

.darkwindow .agreementbox image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

.darkwindow .agreementbox .content {
    box-sizing: border-box;
    padding: 48rpx 32rpx 64rpx;
    position: absolute;
    width: 100%;
    height: 100%;
}

.darkwindow .agreementbox .content .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.darkwindow .agreementbox .content .title .txt {
    color: #202536;
    font-size: 36rpx;
    font-weight: 500;
}

.darkwindow .agreementbox .content .title .close {
    font-size: 44rpx;
    color: #9497B1;
}

.darkwindow .agreementbox .content .ctitle {
    margin-top: 48rpx;
    margin-bottom: 32rpx;
    color: #202536;
    font-weight: 500;
    font-size: 28rpx;
}

.darkwindow .agreementbox .content text {
    color: #9497B1;
    font-size: 28rpx;
    font-weight: 500;
    line-height: 38rpx;
    margin-bottom: 20rpx;
    display: block;
}

.scroll-h {
    height: calc(100vh - 100rpx);
}
</style>

<route lang="json">
{
    "style": {}
}
</route>
